package com.clean.notification.noti;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.KeyguardManager;
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.content.Context;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.media.AudioAttributes;
import android.net.Uri;
import android.os.Build;
import android.os.Handler;
import android.os.Looper;
import android.os.PowerManager;
import android.util.Log;

import androidx.core.app.ActivityCompat;
import androidx.core.app.NotificationCompat;
import androidx.core.app.NotificationManagerCompat;

import com.blankj.utilcode.util.SPUtils;
import com.clean.notification.R;
import com.clean.notification.ShowUtils;
import com.clean.notification.app.BaseApplication;
import com.clean.notification.bean.NotifyDateBean;

import org.jetbrains.annotations.NotNull;

import java.lang.reflect.Method;

import kotlin.jvm.internal.Intrinsics;

/**
 * @author Admin
 */
public class NotifyShowUtils {
    public static final @NotNull Handler mHandler = new Handler(Looper.getMainLooper());
    private static long dayleTime = 4700L;
    public static final int code = 123482;

    private static boolean isShowing = false;

    public static void tryShowLocalPush() {
        if (!isShowing) {
            isShowing = true;
            mHandler.postDelayed(() -> isShowing = false, 3000);
            boolean isForeground = SPUtils.getInstance().getBoolean("isForeground", false);
            Log.e("aaa", "tryShowLocalPush:  是否在前台 " + isForeground);
            if (!isForeground) {
                boolean isEnabled = ShowUtils.INSTANCE.isNotificationEnabled(BaseApplication.mContext);
                if (isEnabled) {
                    NotifyDateBean dateBean = RandomNotifyUtils.notifyItem(BaseApplication.mContext);
                    showSceneNotify(dateBean, true, false);
                    Log.e("aaa", "tryShowLocalPush:  不在冷却期 -- 走悬停通知  ");
                }
            }
        }
    }

    public static boolean showSceneNotify(NotifyDateBean notifyDateBean, boolean isSilent, boolean isIgnoreLastPushTime) {

        NotificationManager mManager = (NotificationManager) BaseApplication.mContext.getSystemService(Context.NOTIFICATION_SERVICE);
        final int notificationId = notifyDateBean.getNotifyId();

        cancelNotificationId(notifyDateBean.getNotifyId());

        String channelId = "Sound_ChannelId" + code;
        String channelName = "Sound_ChannelName" + code;

        if (isSilent) {
            channelId = "SilentChannelId" + code;
            channelName = "SilentChannelName" + code;
        }

        int smallIcon = R.mipmap.logo;

        if (Build.VERSION.SDK_INT >= 26) {
            NotificationChannel channel = new NotificationChannel(channelId, channelName, NotificationManager.IMPORTANCE_HIGH);
            channel.setLockscreenVisibility(1);

            if (isSilent) {
                channel.setDescription("Silent_Apynex");
                channel.enableLights(false);
                channel.enableVibration(false);
                channel.setSound((Uri) null, (AudioAttributes) null);
                channel.setLightColor(0);
                channel.setVibrationPattern(new long[0]);
            } else {
                channel.setDescription("Silent002_Apynex");
                channel.enableLights(false);
                channel.enableVibration(false);
                channel.setLightColor(0);
                channel.setVibrationPattern(new long[0]);
            }

            mManager.createNotificationChannel(channel);
        }

        final NotificationCompat.Builder builder = new NotificationCompat.Builder(BaseApplication.mContext, channelId);
        if (Build.VERSION.SDK_INT >= 31) {
            builder.setCustomBigContentView(notifyDateBean.getRemoteViewsBig());
            builder.setCustomContentView(notifyDateBean.getRemoteViewsMini());
            builder.setContent(notifyDateBean.getRemoteViewsMini());
        } else {
            builder.setCustomContentView(notifyDateBean.getRemoteViewsMid());
            builder.setContent(notifyDateBean.getRemoteViewsMid());
            builder.setCustomBigContentView(notifyDateBean.getRemoteViewsBig());
        }

        builder.setContentText("apex").setAutoCancel(true).setGroupSummary(false).setGroup(String.valueOf(System.currentTimeMillis())).setContentIntent(notifyDateBean.getPendingIntent())
//                .setDeleteIntent(cancelPendingIntent)
                .setBadgeIconType(NotificationCompat.BADGE_ICON_SMALL).setNumber(3).setPriority(1).setVisibility(NotificationCompat.VISIBILITY_PUBLIC).setSmallIcon(smallIcon);
        if (isSilent) {
            builder.setVibrate(new long[0]);
            builder.setLights(0, 0, 0);

            builder.setSound((Uri) null);
        } else {
            builder.setVibrate(new long[0]);
            builder.setLights(0, 0, 0);
        }

        builder.setCategory("call");

        mHandler.postDelayed(() -> {
            NotificationManagerCompat notificationManager = NotificationManagerCompat.from(BaseApplication.mContext);
            if (ActivityCompat.checkSelfPermission(BaseApplication.mContext, Manifest.permission.POST_NOTIFICATIONS) != PackageManager.PERMISSION_GRANTED) {
                return;
            }
            boolean isForeground = SPUtils.getInstance().getBoolean("isForeground", false);
            if (!isForeground){
                notificationManager.notify(notificationId, builder.build());
            }
//            doCycle(notificationManager, notificationId, builder.build());
        }, 1200L);

        return true;
    }

    public static void cancelNotificationId(int notificationId) {
        try {
            NotificationManager mManager = (NotificationManager) BaseApplication.mContext.getSystemService(Context.NOTIFICATION_SERVICE);
            if (notificationId < 0) {
                mManager.cancelAll();
                return;
            }
            mManager.cancel(notificationId);
        } catch (Exception var17) {
            var17.printStackTrace();
        }
    }

    private static void doCycle(final NotificationManagerCompat notificationManager, final int id, final Notification notification) {
        mHandler.postDelayed(() -> {
            boolean isSendOk = doCycleSend(notificationManager, id, notification);
//            if (isSendOk) {
//                mHandler.postDelayed(() -> {
//                    boolean isSendOk12 = doCycleSend(notificationManager, id, notification);
//                }, dayleTime);
//            }
        }, dayleTime);
    }


    @SuppressLint({"MissingPermission"})
    private static boolean doCycleSend(NotificationManagerCompat notificationManager, int id, Notification notification) {
        Log.e("xxx", "----------doCycleSend---------- ");
        // 是否在前台
        boolean isForeground = SPUtils.getInstance().getBoolean("isForeground", false);
        if (!isForeground) {
            // 在前台
            boolean isNotificationEnabled = isNotificationEnabled();
            boolean screenOn = isScreenOn() && isScreenLockOpen();
            if (isNotificationEnabled && screenOn) {
                try {
                    notificationManager.notify(id, notification);
                } catch (Exception var93) {
                    var93.printStackTrace();
                }
                return true;
            } else {
                return false;
            }
        } else {
            return false;
        }
    }


    public static boolean isNotificationEnabled() {
        boolean isEnable = true;
        if (Build.VERSION.SDK_INT >= 26) {
            if (isEnableV26(BaseApplication.mContext)) {
                isEnable = true;
            } else {
                isEnable = false;
            }
        }
        return isEnable;
    }

    private static boolean isEnableV26(Context context) {
        try {
            Object var10000 = context.getSystemService(Context.NOTIFICATION_SERVICE);
            if (var10000 == null) {
                throw new NullPointerException("null cannot be cast to non-null type android.app.NotificationManager");
            } else {
                NotificationManager notificationManager = (NotificationManager) var10000;
                Method sServiceField = notificationManager.getClass().getDeclaredMethod("getService");
                Intrinsics.checkNotNullExpressionValue(sServiceField, "sServiceField");
                sServiceField.setAccessible(true);
                Object sService = sServiceField.invoke(notificationManager);
                ApplicationInfo appInfo = context.getApplicationInfo();
                Context var10 = context.getApplicationContext();
                Intrinsics.checkNotNullExpressionValue(var10, "context.applicationContext");
                String pkg = var10.getPackageName();
                int uid = appInfo.uid;
                Method method = sService.getClass().getDeclaredMethod("areNotificationsEnabledForPackage", String.class, Integer.TYPE);
                Intrinsics.checkNotNullExpressionValue(method, "method");
                method.setAccessible(true);
                var10000 = method.invoke(sService, pkg, uid);
                if (var10000 == null) {
                    throw new NullPointerException("null cannot be cast to non-null type kotlin.Boolean");
                } else {
                    return (Boolean) var10000;
                }
            }
        } catch (Exception var25) {
            var25.printStackTrace();
            return false;
        }
    }

    public static boolean isScreenOn() {
        PowerManager manager = (PowerManager) BaseApplication.mContext.getSystemService(Context.POWER_SERVICE);
        return manager.isInteractive();
    }

    public static boolean isScreenLockOpen() {
        KeyguardManager nKeyguardManager = (KeyguardManager) BaseApplication.mContext.getSystemService(Context.KEYGUARD_SERVICE);
        return !nKeyguardManager.isKeyguardLocked();
    }

}
